package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.web-site}")
    String website;

    @Autowired
    WmNewsMaterialService wmNewsMaterialService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1 检查参数
        if (multipartFile == null || multipartFile.getSize() == 0) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的文件信息");
        }

        //检查用户是否登录

        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2. 上传到OSS
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        fileName = fileName + suffix;

        try {

            //3. 封装数据并保存到素材库

            fileName = fileStorageService.store(prefix, fileName, multipartFile.getInputStream());
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setUserId(wmUser.getId());
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setIsCollection((short) 0);
            wmMaterial.setType((short) 0);
            wmMaterial.setUrl(fileName);

            save(wmMaterial);

            wmMaterial.setUrl(website + wmMaterial.getUrl());

            return ResponseResult.okResult(wmMaterial);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR, "文件上传失败，请稍后重试");
        }
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {

        //1.检查参数

        if (dto == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.搜素

        IPage pageRequest = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = Wrappers.lambdaQuery();

        if (dto.getIsCollection() != null && dto.getIsCollection().intValue() == 1) {
            queryWrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }

        queryWrapper.eq(WmMaterial::getUserId, wmUser.getId())
                .orderByDesc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> pageResult = page(pageRequest, queryWrapper);

        List<WmMaterial> list = pageRequest.getRecords();

        for (WmMaterial wmMaterial : list) {

            wmMaterial.setUrl(website + wmMaterial.getUrl());
        }
        //3.返回
        return new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal(), list);
    }

    @Override
    public ResponseResult deletePicture(Integer id) {
        //1.检查参数

        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 根据id 查询图片信息

        WmMaterial wmMaterial = getById(id);

        if (wmMaterial == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = Wrappers.<WmNewsMaterial>lambdaQuery();

        queryWrapper.eq(WmNewsMaterial::getId, id);
        int count = this.wmNewsMaterialService.count(queryWrapper);
        if (count > 0) {
            throw new CustomException(AppHttpCodeEnum.DATA_EXIST, "图片被调用，无法删除");
        }
        //3. 删除OSS图片
        String url = wmMaterial.getUrl();
//        url = url.replaceAll(website, "");
        fileStorageService.delete(url);
        //4. 删除数据库信息
        removeById(id);
        //5. 返回数据
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult collectionMaterial(Integer id) {
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        return this.updateStatus(id, WemediaConstants.COLLECT_MATERIAL);
    }

    @Override
    public ResponseResult cancelCollectionMaterial(Integer id) {
        if (id == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        return this.updateStatus(id, WemediaConstants.CANCEL_COLLECT_MATERIAL);
    }

    private ResponseResult updateStatus(Integer id, Short collectMaterial) {

        if (id == null || collectMaterial == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (wmUser==null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaUpdateWrapper<WmMaterial> updateWrapper = Wrappers.<WmMaterial>lambdaUpdate();
        updateWrapper.set(WmMaterial::getIsCollection, collectMaterial)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, wmUser.getId());

        update(updateWrapper);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}
